import { floor, divide, subtract, multiply } from 'lodash';

const DEFAULT_SCALE_VALUE = 'auto';
const DEFAULT_SCALE = 1.0;
const MIN_SCALE = 0.1;
const MAX_SCALE = 10.0;
const UNKNOWN_SCALE = 0;
const MIN_AUTO_SCALE = 0.5;
const MAX_AUTO_SCALE = 1.25;

const SCALES_ZOOM = [0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const SCALES_SELECT = [
  'auto',
  'page-actual',
  'page-fit',
  'page-width',
  0.5,
  0.75,
  1.0,
  1.25,
  1.5,
  2,
  3,
  4,
];

const MIN_AUTO_WIDTH = 760;
const MAX_AUTO_WIDTH = 1080;

/**
 * 计算自适应缩放比例
 * @param {number} w1 PDF文档实际宽度
 * @param {number} w2 容器宽度
 * @param {number} h1 PDF文档实际高度
 * @param {number} h2 容器高度
 * @param {number} offsetX 宽度偏移
 * @param {number} offsetY 高度偏移
 */
const calcAutoScale = (w1, w2, h1, h2, offsetX = 100) => {
  const scale = floor(divide(subtract(w2, offsetX), w1), 2);
  const w = multiply(w1, scale);
  if (w > MAX_AUTO_WIDTH) {
    return floor(divide(subtract(MAX_AUTO_WIDTH, offsetX), w1), 2);
  }
  if (w < MIN_AUTO_WIDTH) {
    return floor(divide(subtract(MIN_AUTO_WIDTH, offsetX), w1), 2);
  }

  return scale;
};

const calcRect = (sx, sy, ex, ey, scale = 1) => {
  const x = sx <= ex ? sx : ex;
  const y = sy <= ey ? sy : ey;
  const width = sx <= ex ? subtract(ex - sx) : subtract(sx - ex);
  const height = sy <= ey ? subtract(ey - sy) : subtract(sy - ey);
  return {
    x: floor(divide(x, scale)),
    y: floor(divide(y, scale)),
    width: floor(divide(width, scale)),
    height: floor(divide(height, scale)),
  };
};

export {
  DEFAULT_SCALE_VALUE,
  DEFAULT_SCALE,
  MIN_SCALE,
  MAX_SCALE,
  UNKNOWN_SCALE,
  MAX_AUTO_SCALE,
  SCALES_ZOOM,
  SCALES_SELECT,
  MIN_AUTO_SCALE,
  MIN_AUTO_WIDTH,
  MAX_AUTO_WIDTH,
  calcAutoScale,
  calcRect,
};
